package org.galaxyworld.flycode.dbspy;

import org.apache.commons.lang3.StringUtils;
import org.galaxyworld.flycode.config.SpyConfig;
import org.galaxyworld.flycode.model.Field;
import org.galaxyworld.flycode.model.Table;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class MySQLSpy extends AbstractSpy {

    @Resource
    private SpyConfig spyConfig;

    public List<Table> getTables(String schema) {
        Map<String, String> params = new HashMap<>();
        params.put("schema", schema);
        List<Table> tables = getJdbcTemplate().query(spyConfig.sqlForSelectTables(), params, (ResultSet resultSet, int i) -> {
            Table table = new Table();
            table.setCatalog(resultSet.getString("table_catalog"));
            table.setSchema(resultSet.getString("table_schema"));
            table.setName(resultSet.getString("table_name"));
            table.setComment(resultSet.getString("table_comment"));
            table.setRows(resultSet.getString("table_rows"));
            return table;
        });
        List<Field> fields = getJdbcTemplate().query(spyConfig.sqlForSelectColumnTypes(), params, (ResultSet resultSet, int i) -> {
            Field field = new Field();
            field.setTableName(resultSet.getString("table_name"));
            field.setColumnType(resultSet.getString("column_type"));
            field.setShortColumnType(resultSet.getString("short_column_type"));
            field.setColumnName(resultSet.getString("column_name"));
            field.setConstraintType(resultSet.getString("constraint_type"));
            return field;
        });
        tables.forEach((table) -> {
            List<Field> belonged = fields.stream()
                    .filter(field -> StringUtils.equalsIgnoreCase(field.getTableName(), table.getName()))
                    .collect(Collectors.toList());
            table.setFields(belonged);
        });
        return tables;
    }

}
